package com.edu.controller;

import com.edu.pojo.*;
import com.edu.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;


import com.edu.pojo.Activitie;
import com.edu.pojo.Announcement;
import com.edu.pojo.Member;
import com.edu.pojo.users;
import com.edu.service.*;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;


@Controller
    @RequestMapping(value="/minister")
    public class MinisterController {

        @Autowired
        private MemberService memberService;
        @Autowired
        private com.edu.service.userservice userservice;

        @Autowired
        private DepartmentService departmentService;


        @Autowired
        private CollegeService collegeService;

        @Autowired
        private AnnouncementService announcementService;

        @Autowired
        private ActivitieService activitieService;
        @Autowired
        private MissionService missionService;
        @Autowired
        private MoneyService moneyService;
        @Autowired
        private  SuggestionService suggestionService;
        @Autowired
        private  EquipmentService equipmentService;

        @RequestMapping(value="/main",method= RequestMethod.GET)
        public String ToMainForm() {
            return "Minister/main";
        }

        @RequestMapping(value="/toRepaly")
        public String toAddRepaly(Model model,int id) {
            Suggestion suggestion = suggestionService.querySuggestionById(id);
            model.addAttribute("suggestion",suggestion);
            return "Minister/AddRepaly";
        }

        @RequestMapping(value="/modifyPassword",method=RequestMethod.GET)
        public String ToModifyPassword() {
            return "Minister/MinisterModifyPassword";
        }


        @RequestMapping(value="/addmission",method=RequestMethod.GET)
        public String ToAddMission(Model model,int department) {
            List<Member> list = memberService.showdepartment(department);
            model.addAttribute("department",list);
            return "Minister/AddMission";
        }

    @RequestMapping(value="/checkIncompleteMission",method=RequestMethod.GET)
    public String CheckIncompleteMission(Model model,String memberNo) {

        List<Mission> list = missionService.showNeedMission(1,memberNo);

        for(int i=0;i<list.size();i++) {
            int status = list.get(i).getStatus();
            if(status == 1) {
                list.get(i).setStatusName("未完成");
            }
            list.get(i).setDepartmentNa(memberService.getMemberByNO(list.get(i).getMemberNo()).getStudentName());
//            list.get(i).setDepartmentNa(departmentService.getNameByID(Integer.parseInt(list.get(i).getMemberNo())));
        }


        model.addAttribute("missionList",list);

        return "Minister/IncompleteMission";
    }

    @RequestMapping(value="/checkMission",method=RequestMethod.GET)
    public String CheckMission(Model model,String memberNo) {

        List<Mission> list = missionService.showNeedMission(2,memberNo);

        for(int i=0;i<list.size();i++) {
            int status = list.get(i).getStatus();
            if(status == 2) {
                list.get(i).setStatusName("审核中");
            }
        }

        model.addAttribute("missionList",list);

        return "Minister/MissionManageApp";
    }


    @RequestMapping(value="/checkFinishMission",method=RequestMethod.GET)
    public String checkFinishMission(Model model,String memberNo) {

        List<Mission> list = missionService.showNeedMission(3,memberNo);

        for(int i=0;i<list.size();i++) {
            int status = list.get(i).getStatus();
            if(status == 3) {
                list.get(i).setStatusName("已完成");
            }
        }
        model.addAttribute("missionList",list);

        return "Minister/MissionManage";
    }
    @RequestMapping(value="/notApproved",method=RequestMethod.GET)
    public String ToNotApprovedMission(Model model,int id,String memberNo) {
        missionService.notApproved(id);

        return "redirect:/minister/checkIncompleteMission?memberNo="+memberNo;
    }

    @RequestMapping(value="/approved",method=RequestMethod.GET)
    public String ToApprovedMission(Model model,int id,String memberNo) {
        missionService.approved(id);

        return "redirect:/minister/checkFinishMission?memberNo="+memberNo;
    }

        @RequestMapping(value="/updateequipment")
        public String ToUpdateEquipment(Model model,int id) {
            Equipment equipment =equipmentService.showEqById(id);
            model.addAttribute("equipment",equipment);
            return "Minister/EquipmentModify";
        }

        @RequestMapping(value="/addequipment")
        public String Toaddequipment(Model model,int department) {

            model.addAttribute("department",department);
            return "Minister/AddEquipment";
        }



        @RequestMapping(value="/checkActivity",method=RequestMethod.GET)
        public String CheckActivity(Model model) {
            List<Activitie> activitie = activitieService.queryAllActivitie();

            for(int i=0;i<activitie.size();i++) {
                int status = activitie.get(i).getStatus();
                if(status == 1) {
                    activitie.get(i).setStatusName("未审核");
                }else if(status == 2) {
                    activitie.get(i).setStatusName("审核通过");
                }else {
                    activitie.get(i).setStatusName("未通过");
                }
            }

            model.addAttribute("thesisTitleList", activitie);
            System.out.println("查询到该所以的课题有："+activitie);
            return "chair/CheckActivity";
        }
        @RequestMapping(value="/modifyEquipmentToDb")
        public String ModifyMemberToDb(Model model,HttpServletRequest request, String equipmentName, String position,int department,int id) throws Exception {
            Equipment equipment = new Equipment();
            equipment.setEquipmentName(equipmentName);
            equipment.setPosition(position);
            equipment.setDepartment(department);
            equipment.setId(id);

            SimpleDateFormat time=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date ss =new Date();
            String time4 =time.format(ss.getTime());
            Date formatTime = time.parse(time4);

            equipment.setUpdateTime(formatTime);
             equipmentService.updateEquip(equipment);

            return "redirect:/minister/showequipment?department="+department;
        }
        @RequestMapping(value="/addEquipmentToDb")
        public String addEquipmentToDb(Model model,HttpServletRequest request, String equipmentName, String position,int department) throws Exception {
            Equipment equipment = new Equipment();
            equipment.setEquipmentName(equipmentName);
            equipment.setPosition(position);
            equipment.setDepartment(department);
            SimpleDateFormat time=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date ss =new Date();
            String time4 =time.format(ss.getTime());
            Date formatTime = time.parse(time4);

            equipment.setUpdateTime(formatTime);
            equipmentService.addEquip(equipment);

            return "redirect:/minister/showequipment?department="+department;
        }


        @RequestMapping(value="/showannouncement")
        public String Announcement(Model model) {
            List<Announcement> list = announcementService.queryAnnouncement();
            SimpleDateFormat time=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            for(int i=0;i<list.size();i++) {
                Date time4db = list.get(i).getInputTime();
                String formatTime = time.format(time4db);
                list.get(i).setFormatTime(formatTime);
            }
            model.addAttribute("announcementList", list);
            return "Minister/Announcement";
        }
        @RequestMapping(value="/showsuggestion")
        public String showsuggestion(Model model) {
            List<Suggestion> list = suggestionService.queryAllSuggestion();

            model.addAttribute("suggestionList", list);
            return "Minister/suggestion";
        }
        @RequestMapping(value="/showMinister")
        public String ShowMinister(Model model, HttpServletResponse response, HttpServletRequest request, String id) throws Exception {
            users user = userservice.queryuserById(id);
            HttpSession session = request.getSession();
            session.setMaxInactiveInterval(3600);
            session.setAttribute("user", user);

            Member member = memberService.getMemberByNO(user.getUserid());
            int depId = member.getDepartment();
            String depName = departmentService.getNameByID(depId);
            member.setDepartmentNa(depName);

            int coID = member.getCollegeId();
            String coName = collegeService.getNameByID(coID+"");
            member.setCollegeNa(coName);

            session.setAttribute("member", member);
            return "Minister/MinisterManage";
        }


        @RequestMapping(value="/showMyMission")
        public String showmission(Model model,Integer department) {
            String dep = department+"";
            List<Mission> list =missionService.showMyMission(dep);
            for(int i=0;i<list.size();i++) {
                int status = (list.get(i).getStatus());
                if(status == 1) {
                    list.get(i).setStatusName("未完成");
                }
                    else if(status == 2){
                    list.get(i).setStatusName("审核中");
                }else if(status == 3){
                    list.get(i).setStatusName("已完成");
                }
            }
            model.addAttribute("missionList", list);
            return "Minister/MyMission";
        }

    @RequestMapping(value="/PathFinish")
    public String FinishPath(Integer id,Model model) {
        model.addAttribute("id",id);
        return "Minister/FinishPath";
    }


    @RequestMapping(value="/upload")
    public String upload(HttpServletRequest request, MultipartFile file, Integer id, Model model) throws Exception {

        String localPath = "E:\\Java EE tomcat\\apache-tomcat-9.0.31\\webapps\\filepath\\finishPath\\";
        String exName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String fileName = UUID.randomUUID().toString()+exName;
        FileCopyUtils.copy(file.getInputStream(),new FileOutputStream(new File(localPath+fileName)));

        missionService.finishMission(localPath+fileName,id);
        missionService.agreeThesisTitle(id);

        Mission m =missionService.querymissionById(id);
        String memberNo =m.getMemberNo();

        return "redirect:/minister/showMyMission?department="+memberNo;


    }

        @RequestMapping(value="/agreeThesis")
        public String agreeThesis(int id,Model model,String memberNo) {

             missionService.agreeThesisTitle(id);
            return "redirect:/minister/showMyMission?memberNo="+memberNo;
        }
        @RequestMapping(value="/showAllMission")
        public String showAllmission(Model model,String memberNo) {
            List<Mission> list =missionService.showAllMission(memberNo);
            for(int i=0;i<list.size();i++) {
                int status = (list.get(i).getStatus());
                if(status == 1) {
                    list.get(i).setStatusName("未接受");
                }else if(status == 2) {
                    list.get(i).setStatusName("已接受");
                }else if(status == 4){
                    list.get(i).setStatusName("已完成");
                }else if(status == 3){
                    list.get(i).setStatusName("审核中");
                }else if(status == 5){
                    list.get(i).setStatusName("未通过");
                }
            }
            model.addAttribute("missionList", list);
            return "Minister/AllMission";
        }



        @RequestMapping(value="/modifyMinister")
        public String adminModifyMinister(String id,Model model) {
            Member member = memberService.getMemberByNO(id);

            String memberNo = member.getMemberNo();
            String studentName = member.getStudentName();
            int depId = member.getDepartment();
            String departmentName = departmentService.getNameByID(depId);
            String sex = member.getSex();
            int collegeId =member.getCollegeId();
            String phone = member.getPhone();
            int permssion = member.getPermssion();

            model.addAttribute("memberNo", memberNo);
            model.addAttribute("studentName", studentName);
            model.addAttribute("departmentName", departmentName);
            model.addAttribute("sex", sex);
            model.addAttribute("phone", phone);
            model.addAttribute("collegeId", collegeId);
            model.addAttribute("permssion", permssion);
            return "Minister/MinisterModify";
        }

        @RequestMapping(value="/modifyMinisterToDb")
        public String ModifyMinisterToDb(Model model,HttpServletRequest request, String memberNo, String studentName,String sex,String phone,String depart,String collegeId) throws Exception {
            Member member = new Member();
            member.setMemberNo(memberNo);
            member.setStudentName(studentName);
            member.setSex(sex);
            member.setCollegeId(Integer.parseInt(collegeId));
            member.setPhone(phone);
            member.setDepartment(Integer.parseInt(depart));
            member.setPermssion(2);

            memberService.updateStudent(member);

            return "redirect:/minister/showMinister?id="+memberNo;
        }
        @RequestMapping(value="/showdepartment")
        public String ShowAllMember(Model model,HttpServletResponse response,int department) throws Exception {
            List<Member> members = memberService.showdepartment(department);
            for(int i=0;i<members.size();i++) {
                System.out.println(members.get(i));
                int depaId = members.get(i).getDepartment();
                String depaNa = departmentService.getNameByID(depaId);
                members.get(i).setDepartmentNa(depaNa);
            }
            model.addAttribute("memberList", members);
            System.out.println("全部成员集合："+members);
            return "Minister/MinisterMemberList";
        }
        @RequestMapping(value="/showequipment")
        public String showEquipment(Model model,HttpServletResponse response,int department) throws Exception {
            List<Equipment> equipment = equipmentService.showAllEquip(department);
            for(int i=0;i<equipment.size();i++) {
                System.out.println(equipment.get(i));
                int depaId = equipment.get(i).getDepartment();
                String depaNa = departmentService.getNameByID(depaId);
                equipment.get(i).setDepartmentNa(depaNa);
            }
            model.addAttribute("equipmentList", equipment);
            System.out.println("全部成员集合："+equipment);
            return "Minister/MinisterEqupmentList";
        }


        @RequestMapping(value="/MinisterAdd",method=RequestMethod.POST)
        public String addMember(HttpServletRequest request, MultipartFile file, String missionName, String context, String memberNo, String publishman, Model model, int department) throws Exception {
            Mission mission =new Mission();
            mission.setMissionName(missionName);
            mission.setContext(context);

            SimpleDateFormat time=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date ss =new Date();
            String time4 =time.format(ss.getTime());
            Date formatTime = time.parse(time4);

            mission.setInputTime(formatTime);

            mission.setStatus(1);
            mission.setPublishman(publishman);
            mission.setMemberNo(memberNo);

            String localPath = "E:\\Java EE tomcat\\apache-tomcat-9.0.31\\webapps\\filepath\\missionPath\\";
            String exName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            String fileName = UUID.randomUUID().toString()+exName;
            FileCopyUtils.copy(file.getInputStream(),new FileOutputStream(new File(localPath+fileName)));

            mission.setMissionPath(localPath+fileName);
            missionService.addMission(mission);
            return "redirect:/minister/checkIncompleteMission?memberNo="+publishman;
        }
        @RequestMapping(value="/deletemission")
        public String deletemission(int id,int department,String memberNo) throws Exception {

            missionService.deleteMission(id);
            return "redirect:/minister/showAllMission?memberNo="+memberNo;
        }


        @RequestMapping(value="/addReplyDB")
        public String addReplyDB(HttpServletRequest request, int id, String reply) throws Exception {
            System.out.println(reply);


            suggestionService.addReply(reply,id);

            return "redirect:/minister/showsuggestion";
        }
        @RequestMapping(value="/checkapplication")
        public String checkapplication(Model model,String memberNo) {
            List<Money> list =moneyService.showMyApplication(memberNo);

            for(int i=0;i<list.size();i++) {
                int status = list.get(i).getStatus();
                if(status == 1) {
                    list.get(i).setStatusName("未接受");
                }else if(status == 2){
                    list.get(i).setStatusName("通过");
                }else if(status == 3){
                    list.get(i).setStatusName("未通过");
                }
            }
            model.addAttribute("applicationList", list);
            return "Minister/MyApplication";
        }
        @RequestMapping(value="/addapplication",method=RequestMethod.GET)
        public String Toaddapplication(Model model) {

            return "Minister/AddApplication";
        }

        @RequestMapping(value="/applicationAdd",method=RequestMethod.POST)
        public String applicationAdd(HttpServletRequest request, String money, String cause,String memberNo,Model model) throws Exception {
            Money mon =new Money();
            int mone = Integer.parseInt(money);
            mon.setMoney(mone);
            mon.setCause(cause);

            SimpleDateFormat time=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date ss =new Date();
            String time4 =time.format(ss.getTime());
            Date formatTime = time.parse(time4);

            mon.setInputTime(formatTime);

            mon.setStatus(1);

            mon.setMemberNo(memberNo);
            moneyService.addOperation(mon);
            return "redirect:/minister/checkapplication?memberNo="+memberNo;
        }









//	@RequestMapping(value="/fileDownload")
//	public ResponseEntity<byte[]> fileDownload(HttpServletRequest request, @RequestParam("filePath") String filePath,@RequestParam("fileName") String fileName, Model model) throws Exception {
//		fileName = new String(fileName.getBytes("iso-8859-1"),"utf-8");
//		filePath = new String(filePath.getBytes("iso-8859-1"),"utf-8");
//		File file = new File(filePath);
//		HttpHeaders headers = new HttpHeaders();
//		String downloadFile = new String(fileName.getBytes("utf-8"), "iso-8859-1");
//		headers.setContentDispositionFormData("attachment", downloadFile);
//		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
//		return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers,HttpStatus.CREATED);
//	}



    }


